package com.lvs.zmwz.service.impl;

import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lvs.zmwz.comm.DictionaryEnum;
import com.lvs.zmwz.comm.ResultEnum;
import com.lvs.zmwz.entity.SysManager;
import com.lvs.zmwz.entity.SysRole;
import com.lvs.zmwz.entity.req.SysManagerReq;
import com.lvs.zmwz.entity.serach.SysManagerSearch;
import com.lvs.zmwz.exception.MyException;
import com.lvs.zmwz.mapper.SysManagerMapper;
import com.lvs.zmwz.service.ISysManagerRoleService;
import com.lvs.zmwz.service.ISysManagerService;
import com.lvs.zmwz.service.ISysRoleService;
import com.lvs.zmwz.util.IdentityUtil;
import com.lvs.zmwz.util.QPage;
import com.lvs.zmwz.util.ResultView;
import com.lvs.zmwz.util.RsaUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

/**
 * <p>
 * 后台账户表 服务实现类
 * </p>
 *
 * @author astupidcoder
 * @since 2021-06-16
 */
@Service
public class SysManagerServiceImpl extends ServiceImpl<SysManagerMapper, SysManager> implements ISysManagerService {

    @Autowired
    private ISysManagerRoleService iHjManagerRoleService;
    @Autowired
    private ISysRoleService iHjRoleService;
    /**
     * 获取管理用户列表
     * @param qPage
     * @param hjManagerSearch
     * @return
     */
    @Override
    public IPage<SysManager> getListAll(QPage qPage, SysManagerSearch hjManagerSearch) {
        QueryWrapper<SysManager> queryWrapper=new QueryWrapper<>();
        queryWrapper.lambda().like(StringUtils.isNotEmpty(hjManagerSearch.getMAccount()),SysManager::getMAccount,hjManagerSearch.getMAccount());
        queryWrapper.lambda().like(StringUtils.isNotEmpty(hjManagerSearch.getMPhone()),SysManager::getMPhone,hjManagerSearch.getMPhone());
        queryWrapper.lambda().like(StringUtils.isNotEmpty(hjManagerSearch.getMName()),SysManager::getMName,hjManagerSearch.getMName());
        queryWrapper.eq("is_del", DictionaryEnum.IS_DEL_N.getCode());
        queryWrapper.orderByDesc("ctime");
        IPage<SysManager> hjManagerIPage=this.page(new Page<>(qPage.getOffset(), qPage.getLimit()),queryWrapper);
        return hjManagerIPage;
    }

    /**
     * 新增用户
     * @param hjManagerReq
     * @return
     */
    @Transactional
    @Override
    public ResultView addManager(SysManagerReq hjManagerReq) {
        //检测当前账户是否存在
        SysManager exit=exitAccount(hjManagerReq.getMAccount());
        if(exit!=null){
            return ResultView.error("此账户已经存在");
        }
        SysManager hjManager=new SysManager();
        BeanUtils.copyProperties(hjManagerReq,hjManager);
        hjManager.setMPwd(RsaUtil.setRsaPwd(hjManagerReq.getMPwd()));
        hjManager.setManagerId(IdentityUtil.identityId("MA"));
        hjManager.setCtime(new Date());
        hjManager.setIsDel(DictionaryEnum.IS_DEL_N.getCode());
        hjManager.setMType(DictionaryEnum.MANAGER_SUPER_ADMIN.getCode());
        boolean count=this.save(hjManager);
        if(!count){
            throw new MyException(ResultEnum.CODE_2,"添加用户出现异常");
        }
        //新增用户角色关联表
        boolean isOk=this.iHjManagerRoleService.saveRoleUser(hjManagerReq.getRoleId(),hjManager.getManagerId());
        if(!isOk){
            throw new MyException(ResultEnum.CODE_2,"添加用户角色关联出现异常");
        }
        return ResultView.ok();
    }

    /**
     * 检测当前账户是否存在
     * @param account
     * @return
     */
    @Override
    public SysManager exitAccount(String account) {
        QueryWrapper<SysManager> queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("m_account",account);
        queryWrapper.eq("is_del",DictionaryEnum.IS_DEL_N.getCode());
        SysManager hjManager=this.getOne(queryWrapper);
        return hjManager;
    }

    /**
     * 启用或停用账户
     * @param managerId
     * @return
     */
    @Override
    public ResultView applyStatus(String managerId) {
        SysManager hjManager=this.getById(managerId);
        if(hjManager==null){
            return ResultView.error("账户不存在");
        }
        if(hjManager.getMStatus()==DictionaryEnum.IS_ENABLE_N.getCode()){
            hjManager.setMStatus(DictionaryEnum.IS_ENABLE_Y.getCode());
        }else{
            hjManager.setMStatus(DictionaryEnum.IS_ENABLE_N.getCode());
        }
        boolean isOk=this.updateById(hjManager);
        if(!isOk){
            throw new MyException(ResultEnum.CODE_2,"状态更新异常");
        }
        return ResultView.ok();
    }

    /**
     * 重置密码
     * @param managerId 账户ID
     * @param mPwd 密码
     * @return
     */
    @Override
    public ResultView restPwd(String managerId, String mPwd) {
        SysManager hjManager=this.getById(managerId);
        if(hjManager==null){
            return ResultView.error("账户不存在");
        }
        hjManager.setMPwd(RsaUtil.setRsaPwd(mPwd));
        boolean isOk=this.updateById(hjManager);
        if(!isOk){
            throw new MyException(ResultEnum.CODE_2,"重置密码更新异常");
        }
        return ResultView.ok();
    }

    /**
     * 删除用户
     * @param managerId
     * @return
     */
    @Override
    public ResultView deleteManager(String managerId) {
        SysManager hjManager=this.getById(managerId);
        if(hjManager==null){
            return ResultView.error("账户不存在");
        }
        hjManager.setIsDel(DictionaryEnum.IS_DEL_Y.getCode());
        boolean isOk=this.updateById(hjManager);
        if(!isOk){
            throw new MyException(ResultEnum.CODE_2,"删除用户异常");
        }
        return ResultView.ok();
    }

    /**
     * 根据账户ID获取当前账户信息
     * @return
     */
    @Override
    public ResultView getManagerId(String managerId) {
        Map<String,Object> map=new HashMap<>();
        //获取当前用户信息
        SysManager hjManager=this.getById(managerId);
        map.put("hjManager",hjManager);
        //获取系统中所有的角色
        List<SysRole> roles=this.iHjRoleService.getListAll();
        map.put("roles",roles);
        //获取当前用户已经绑定的角色
        List<Object> roleManager=iHjManagerRoleService.getByRoleId(managerId);
        map.put("roleManager",roleManager);
        return ResultView.ok(map);
    }

    /**
     * 修改账户
     * @param hjManagerReq
     * @return
     */
    @Transactional
    @Override
    public ResultView updateManager(SysManagerReq hjManagerReq) {
        SysManager hjManager=new SysManager();
        BeanUtils.copyProperties(hjManagerReq,hjManager);
        hjManager.setUtime(new Date());
        boolean count=this.updateById(hjManager);
        if(!count){
            throw new MyException(ResultEnum.CODE_2,"修改账户出现异常");
        }
        //删除之前关联这个账户关联的角色数据
        this.iHjManagerRoleService.removeManagerRoleId(hjManagerReq.getManagerId());
        //新增用户角色关联表
        boolean isOk=this.iHjManagerRoleService.saveRoleUser(hjManagerReq.getRoleId(),hjManagerReq.getManagerId());
        if(!isOk){
            throw new MyException(ResultEnum.CODE_2,"添加用户角色关联出现异常");
        }
        return ResultView.ok();
    }

    /**
     * 批量删除用户
     * @param managerId
     * @return
     */
    @Override
    public ResultView batchDeleteManager(String[] managerId) {
        List<SysManager> hjManagerList=new ArrayList<>();
        for (String mId : managerId) {
            SysManager hjManager=new SysManager();
            hjManager.setManagerId(mId);
            hjManager.setIsDel(DictionaryEnum.IS_DEL_Y.getCode());
            hjManagerList.add(hjManager);
        }
        boolean isOk=this.updateBatchById(hjManagerList);
        if(!isOk){
            throw new MyException(ResultEnum.CODE_2,"批量删除用户出现异常");
        }
        return ResultView.ok();
    }


    @Override
    public List<SysManager> manageList() {
        QueryWrapper<SysManager> queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("is_del", DictionaryEnum.IS_DEL_N.getCode());
        queryWrapper.orderByDesc("ctime");
        List<SysManager> sysManagerList=this.list(queryWrapper);
        return sysManagerList;
    }

    /**
     * 根据账户获取当前是否属于内部企业成员账户
     * @param account
     * @return
     */
    @Override
    public SysManager getByUserId(String account) {
        QueryWrapper<SysManager> queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("m_account",account);
        queryWrapper.eq("is_del", DictionaryEnum.IS_DEL_N.getCode());
        SysManager sysManager=this.getOne(queryWrapper);
        return sysManager;
    }


}
